<template>
  <div class="main-content">
    <!-- 统计信息展示区域 -->
    <div class="bg-white p-6 rounded-lg shadow-sm mb-6">
      <div class="grid grid-cols-1 md:grid-cols-6 gap-4 text-center">
        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('partition')"
        >
          <p class="text-gray-500 mb-1">分区</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.zoneCount || 0 }}
          </p>
        </div>
        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('user')"
        >
          <p class="text-gray-500 mb-1">用户</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.userCount || 0 }}
          </p>
        </div>
        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('channel')"
        >
          <p class="text-gray-500 mb-1">频道</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.channelCount || 0 }}
          </p>
        </div>

        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('device')"
        >
          <p class="text-gray-500 mb-1">设备</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.deviceCount || 0 }}
          </p>
        </div>
        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('timeSlice')"
        >
          <p class="text-gray-500 mb-1">时间片</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.timeSliceCount || 0 }}
          </p>
        </div>
        <div
          class="p-4 border rounded-lg cursor-pointer hover:shadow-md transition-shadow"
          @click="handleStatisticClick('userClassify')"
        >
          <p class="text-gray-500 mb-1">分类</p>
          <p class="text-2xl font-bold text-blue-600">
            {{ statisticsData.userCategorizeCount || 0 }}
          </p>
        </div>
      </div>
    </div>
    <el-tabs
      v-model="activeTab"
      type="card"
      class="mt-4 hidden-tabs"
      @tab-change="handleTabChange"
    >
      <!-- 保持原有tab内容不变 -->
      <el-tab-pane label="频道管理" name="channel">
        <component
          :is="loadedComponents.channel"
          v-if="loadedComponents.channel"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
        />
      </el-tab-pane>
      <!-- 其他tab项保持不变 -->
      <el-tab-pane label="分区管理" name="partition">
        <component
          :is="loadedComponents.partition"
          v-if="loadedComponents.partition"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
          :dealerName="dealerName"
        />
      </el-tab-pane>
      <el-tab-pane label="用户管理" name="user">
        <component
          :is="loadedComponents.user"
          v-if="loadedComponents.user"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
        />
      </el-tab-pane>
      <el-tab-pane label="用户分类" name="userClassify">
        <component
          :is="loadedComponents.userClassify"
          v-if="loadedComponents.userClassify"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
        />
      </el-tab-pane>
      <el-tab-pane label="设备管理" name="device">
        <component
          :is="loadedComponents.device"
          v-if="loadedComponents.device"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
          :dealerName="dealerName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="设备关联" name="deviceRelation">
        <component
          :is="loadedComponents.deviceRelation"
          v-if="loadedComponents.deviceRelation"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
          :dealerName="dealerName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="设备分组" name="deviceGroup">
        <component
          :is="loadedComponents.deviceGroup"
          v-if="loadedComponents.deviceGroup"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
          :dealerName="dealerName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="事件管理" name="event">
        <component
          :is="loadedComponents.event"
          v-if="loadedComponents.event"
          :lesseeId="lesseeId"
          :tenantName="tenantName"
          :dealerId="dealerId"
          :dealerName="dealerName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="触发条件" name="condition">
        <component
          :is="loadedComponents.condition"
          v-if="loadedComponents.condition"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="执行动作" name="action">
        <component
          :is="loadedComponents.action"
          v-if="loadedComponents.action"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="任务管理" name="task">
        <component
          :is="loadedComponents.task"
          v-if="loadedComponents.task"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
          :dealerName="dealerName"
          :tenantName="tenantName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="资源管理" name="resource">
        <component
          :is="loadedComponents.resource"
          v-if="loadedComponents.resource"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
          :dealerName="dealerName"
          :tenantName="tenantName"
        />
      </el-tab-pane>
      <el-tab-pane v-if="false" label="触发器管理" name="trigger">
        <component
          :is="loadedComponents.trigger"
          v-if="loadedComponents.trigger"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
          :dealerName="dealerName"
          :tenantName="tenantName"
        />
      </el-tab-pane>
      <el-tab-pane label="时间切片管理" name="timeSlice">
        <component
          :is="loadedComponents.timeSlice"
          v-if="loadedComponents.timeSlice"
          :lesseeId="lesseeId"
          :dealerId="dealerId"
          :dealerName="dealerName"
          :tenantName="tenantName"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  defineAsyncComponent,
  shallowRef,
  onBeforeUnmount,
  watch
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { Message } from "element-plus";

defineOptions({
  name: "SystemLesseesDetail"
});

const route = useRoute();
const router = useRouter();
const activeTab = ref("partition");
const loadedComponents = shallowRef<{ [key: string]: any }>({});
const permissionStore = usePermissionStoreHook();
const multiTagsStore = useMultiTagsStoreHook();

// 统计数据
const statisticsData = ref({
  partitionCount: 0,
  zoneCount: 0,
  userCount: 0,
  channelCount: 0,
  deviceCount: 0,
  userCategorizeCount: 0,
  onlineCount: 0,
  fenceCount: 0,
  timeSliceCount: 0
});

// 组件映射表 - 使用defineAsyncComponent预定义
const componentMap = {
  user: defineAsyncComponent(() => import("./components/userTable.vue")),
  userClassify: defineAsyncComponent(
    () => import("./components/userClassifyTable.vue")
  ),
  channel: defineAsyncComponent(() => import("./components/channelTable.vue")),
  partition: defineAsyncComponent(
    () => import("./components/partitionTable.vue")
  ),
  device: defineAsyncComponent(() => import("./components/deviceTable.vue")),
  deviceRelation: defineAsyncComponent(
    () => import("./components/deviceRelationTable.vue")
  ),
  deviceGroup: defineAsyncComponent(
    () => import("./components/deviceGroupTable.vue")
  ),
  channelMembers: defineAsyncComponent(
    () => import("./components/channelMembersTable.vue")
  ),
  event: defineAsyncComponent(() => import("./components/eventTable.vue")),
  condition: defineAsyncComponent(
    () => import("./components/conditionTable.vue")
  ),
  action: defineAsyncComponent(
    () => import("./components/eventActionTable.vue")
  ),
  task: defineAsyncComponent(() => import("./components/taskTable.vue")),
  resource: defineAsyncComponent(
    () => import("./components/resourceTable.vue")
  ),
  trigger: defineAsyncComponent(() => import("./components/triggerTable.vue")),
  timeSlice: defineAsyncComponent(
    () => import("./components/timeSliceTable.vue")
  )
};

// 获取路由参数中的租户信息
const lesseeInfo = route.query;
let lesseeId = Number(lesseeInfo.Id || 0);
// 确保tenantName始终是字符串类型
let tenantName =
  typeof lesseeInfo.Name === "string"
    ? lesseeInfo.Name
    : String(lesseeInfo.Name || "");
const dealerId = ref(0);
const dealerName = ref("");

// 从sessionStorage恢复数据 - 改进版本
function restoreLesseeData() {
  const savedData = sessionStorage.getItem(`currentLesseeData_${lesseeId}`);
  if (savedData) {
    try {
      const parsed = JSON.parse(savedData);
      if (parsed.lesseeId) {
        lesseeId = parsed.lesseeId;
      }
      if (parsed.tenantName) {
        tenantName = parsed.tenantName;
      }
      if (parsed.dealerId !== undefined) {
        dealerId.value = parsed.dealerId;
      }
      if (parsed.dealerName) {
        dealerName.value = parsed.dealerName;
      }
    } catch (e) {
      console.error("恢复租户数据失败:", e);
    }
  }
}

// 保存租户数据到sessionStorage - 改进版本
function saveLesseeData() {
  if (lesseeId || tenantName) {
    const dataToSave = {
      lesseeId,
      tenantName,
      dealerId: dealerId.value,
      dealerName: dealerName.value
    };
    sessionStorage.setItem(
      `currentLesseeData_${lesseeId}`,
      JSON.stringify(dataToSave)
    );
  }
}

// 核心功能：更新标签页标题为租户名称
function updateTabTitle() {
  if (!tenantName) return;

  // 为动态租户名称添加特殊前缀，避免国际化处理
  const dynamicTitle = `dynamic.${tenantName}`;

  // 查找当前路由对应的标签页（根据路径和完整的query参数）
  const currentTagIndex = multiTagsStore.multiTags.findIndex(
    tag =>
      tag.path === route.path &&
      JSON.stringify(tag.query) === JSON.stringify(route.query)
  );

  if (currentTagIndex !== -1) {
    // 如果找到对应的标签页，则更新标题
    const updatedTags = [...multiTagsStore.multiTags];
    updatedTags[currentTagIndex] = {
      ...updatedTags[currentTagIndex],
      meta: {
        ...updatedTags[currentTagIndex].meta,
        title: dynamicTitle,
        hiddenTag: false // 确保标签页可见
      }
    };

    // 更新标签页
    multiTagsStore.handleTags("equal", updatedTags);
  } else {
    // 如果标签页不存在，则添加新标签页
    const currentTag = {
      path: route.path,
      name: route.name,
      query: route.query,
      meta: {
        ...route.meta,
        title: dynamicTitle,
        hiddenTag: false // 确保标签页可见
      }
    };
    multiTagsStore.handleTags("push", currentTag);
  }

  // 同时设置document.title确保浏览器标题也更新
  document.title = `${tenantName} - 租户详情`;
}

// 修改getTenantParent函数，确保使用最新的lesseeId
async function getTenantParent() {
  if (!lesseeId) {
    console.log("租户ID无效", { type: "warning" });
    return;
  }

  http
    .get(changeHttpLink(`/api/Tenant/${lesseeId}/dealer`), {
      params: { Id: lesseeId }
    })
    .then((res: any) => {
      if (res.Success) {
        dealerId.value = res.Data.Id;
        dealerName.value = res.Data.Name;
        saveLesseeData();
        // 获取数据后再次更新标签页标题
        updateTabTitle();
      } else {
        console.log(res.Message, { type: "error" });
      }
    })
    .catch(err => {
      console.log(err.message, { type: "error" });
    });
}

// 处理标签切换
function handleTabChange(tabName: string) {
  activeTab.value = tabName;
  loadComponent(tabName);
}

// 处理统计卡片点击
function handleStatisticClick(tabName: string) {
  activeTab.value = tabName;
  loadComponent(tabName);
}

// 加载组件
function loadComponent(tabName: string) {
  if (
    componentMap[tabName as keyof typeof componentMap] &&
    !loadedComponents.value[tabName]
  ) {
    // 直接使用预定义的异步组件
    const asyncComponent = componentMap[tabName as keyof typeof componentMap];

    // 创建新对象以触发shallowRef更新
    loadedComponents.value = {
      ...loadedComponents.value,
      [tabName]: asyncComponent
    };
  }
}
//获取租户详情
function getStatisticsData() {
  http
    .get(changeHttpLink(`/api/Tenant/${lesseeId}/statistics`), {
      params: {
        id: lesseeId
      }
    })
    .then((res: any) => {
      if (res.Success) {
        const statistics = res.Data;
        console.log(statistics);
        // 更新统计数据
        statisticsData.value = {
          partitionCount: 0, // 暂时显示0
          zoneCount: statistics.ZoneCount || 0,
          userCount: statistics.UserCount || 0,
          channelCount: statistics.ChannelCount || 0,
          deviceCount: statistics.DeviceCount || 0,
          userCategorizeCount: statistics.UserCategorizeCount || 0,
          onlineCount: 0, // 暂时显示0
          fenceCount: 0, // 暂时显示0
          timeSliceCount: statistics.TenantTimesliceCount || 0
        };
      } else {
        //Message(res.Message, { type: "error" });
      }
    })
    .catch(err => {
      //Message(err.message, { type: "error" });
    });
}
// 监听路由参数变化，确保打开不同租户时能正确识别
watch(
  () => [route.path, route.query],
  () => {
    const newLesseeInfo = route.query;
    const newLesseeId = Number(newLesseeInfo.Id || 0);
    const newTenantName =
      typeof newLesseeInfo.Name === "string"
        ? newLesseeInfo.Name
        : String(newLesseeInfo.Name || "");

    if (newLesseeId !== lesseeId || newTenantName !== tenantName) {
      lesseeId = newLesseeId;
      tenantName = newTenantName;
      restoreLesseeData();
      if (lesseeId) {
        getTenantParent();
      }
      updateTabTitle();
    }
  },
  { deep: true }
);

// 组件挂载时执行
onMounted(() => {
  getStatisticsData();
  // 注释掉页面缓存，避免缓存问题
  // permissionStore.cacheOperate({ mode: "add", name: "SystemLesseesDetail" });

  // 先尝试恢复数据
  restoreLesseeData();

  // 如果有有效的租户ID，加载组件和获取数据
  if (lesseeId) {
    loadComponent(activeTab.value);
    getTenantParent();
  }

  // 确保页面标题正确显示
  if (tenantName) {
    updateTabTitle();
  }

  if (!lesseeId) {
    console.log("租户ID无效", { type: "warning" });
  }
});

// 组件卸载时执行 - 关键点：不要移除缓存
onBeforeUnmount(() => {
  saveLesseeData();
  // 注意：不要在这里调用permissionStore.cacheOperate来删除缓存，以便下次进入时保持状态
  // 系统会通过permissionStore中的debounce监听自动管理缓存
});
</script>

<style lang="scss" scoped>
.main-content {
  margin: 24px 24px 0 !important;
}

.page-title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.hidden-tabs {
  :deep(.el-tabs__header) {
    display: none;
  }
}
</style>
